package com.mall.struts.action;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mall.ibatis.bean.Function;
import com.mall.ibatis.bean.Method;
import com.mall.ibatis.bean.ReturnMessage;
import com.mall.ibatis.bean.Role;
import com.mall.service.FunctionService;
import com.mall.service.RoleService;
import com.thoughtworks.xstream.XStream;


public class RoleAction extends Action
{
	private static Log logger = LogFactory.getLog(RoleAction.class);
	private static final RoleService roleService =  RoleService.getInstance();
	private static final FunctionService functionService = FunctionService.getInstance();
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		String method = request.getParameter("type");
		try
		{
			if(method == null)
			{
				return load(mapping, form, request, response);
			}
			else if(method.equals("query"))
			{
				return query(mapping, form, request, response);
			}
			else if(method.equals("list"))
			{
				return list(mapping, form, request, response);
			}
			else if(method.equals("listAll"))
			{
				return listAll(mapping, form, request, response);
			}
			else if(method.equals("insert"))
			{
				return insert(mapping, form, request, response);
			}
			else if(method.equals("update"))
			{
				return update(mapping, form, request, response);
			}
			else if(method.equals("delete"))
			{
				return delete(mapping, form, request, response);
			}
			else if(method.equals("queryByOperator"))
			{
				return queryByOperator(mapping, form, request, response);
			}
			else if(method.equals("updateOperaotrRole"))
			{
				return updateOperaotrRole(mapping, form, request, response);
			//ryh
			}else if("methodTree".equals(method)){
				return methodTree(mapping,form,request,response);
			}else if("addMethod".equals(method)){
				return addMethod(mapping,form,request,response);
			}else if("methodIsCheck".equals(method)){
				return methodIsCheck(mapping,form,request,response);
			}
			//ryh
		}
		catch (Exception e)
		{
			// TODO: handle exception
			request.setAttribute("exceptionMsg", e.getMessage());
			logger.error(e);
			return mapping.findForward("exceptionError");
		}
		
		return mapping.findForward("pageNotFoundError");
		
	}
	//ryh
	//向服务器请求勾选了哪些功能方法并返回给修改树状窗口
	private ActionForward methodIsCheck(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		String xmlString = roleService.methodIsCheck(id);
		response.setContentType("text/xml;charset=UTF-8");
//		System.out.println(xmlString);
		PrintWriter out = response.getWriter();
		out.print(xmlString);
		out.flush();
		out.close();
		return null;
	}

	//保存方法和功能的关系
	private ActionForward addMethod(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws Exception{
		String str = request.getParameter("str");
		String id = request.getParameter("id");//角色ID
		String functionStr = request.getParameter("functionStr");
		ReturnMessage message = roleService.addMethod(str,id,functionStr);
		
		response.setContentType("text/xml");
		PrintWriter out = response.getWriter();
		out.print(message.toXMLString());
		out.flush();
		out.close();
		return null;
	}
	
	//方法列表的选择查询对话框
	private ActionForward methodTree(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response){
		//可以重复利用查询已勾选过的功能方法
		List<Function> list = roleService.roleLook();
		//查询出每个功能模块中有哪些方法
		List<Method> methods = roleService.selectAllMethod();
		for(Function f : list){
			List<Method> list2 = new ArrayList<Method>();
			for(Method m : methods){
				if(f.getFunctionID().equals(m.getFunId())){
					list2.add(new Method(m.getId(),m.getName()));
				}
			}
			f.setMethods(list2);
			//f.setMethods(methods);
		}
		request.setAttribute("functionList",list);
		return mapping.findForward("roleMethodTree");
	}

	//ryh
	private ActionForward load(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		functionService.methodFilter(request,response);
		return mapping.findForward("loading");
	}
	
	private ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		
		String ID =request.getParameter("ID");
		Role role  =new Role();
		role.setID(ID);
		
		String reponseXML = roleService.selectRole(role).toXML();
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;

	}
	
	
	
	private ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String reponseXML = null;
		
		List<Role> roleList = roleService.selectAllRole();
		
		reponseXML = roleService.getRoleList(roleList, 1, 1).toXML();
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
	}
	
	private ActionForward listAll(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String reponseXML = null;
		
		List<Role> roleList = roleService.selectAllRole();
		
		XStream xStream = new XStream();
		xStream.alias("Role", Role.class);
		xStream.toXML(roleList);
		
		
		reponseXML = xStream.toXML(roleList);
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
	}
	
	private ActionForward insert(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String name =request.getParameter("name");
		
		Role role = new Role();
		role.setName(name);
		ReturnMessage returnMessage=null;
		
		try
		{
			roleService.insertRole(role);
			returnMessage = new ReturnMessage("1",role.getID());
		}
		catch (Exception e)
		{
			// TODO: handle exception
			returnMessage = new ReturnMessage("0",e.getMessage());
			logger.error(e);
		}
		
		String reponseXML = returnMessage.toXMLString();
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
	}
	
	private ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String ID =request.getParameter("ID");
		String name =request.getParameter("name");
		
		Role role = new Role();
		role.setID(ID);
		role.setName(name);
		ReturnMessage returnMessage=null;
		
		try
		{
			roleService.updateRole(role);
			returnMessage = new ReturnMessage("1","");
		}
		catch (Exception e)
		{
			// TODO: handle exception
			returnMessage = new ReturnMessage("0",e.getMessage());
			logger.error(e);
		}
		
		String reponseXML = returnMessage.toXMLString();
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
	}
	
	private ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String ID =request.getParameter("ID");
		Role role  =new Role();
		role.setID(ID);
		ReturnMessage returnMessage=null;
		
		try
		{
			roleService.deleteRole(role);
			returnMessage = new ReturnMessage("1","");
		}
		catch (Exception e)
		{
			// TODO: handle exception
			returnMessage = new ReturnMessage("0",e.getMessage());
			logger.error(e);
		}
		
		String reponseXML = returnMessage.toXMLString();
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
	}
	
	
	private ActionForward queryByOperator(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		
		String operatorID = request.getParameter("operatorID");
		
		String reponseXML = null;
		
		
		List<Role> roleList = roleService.selectRolesByOperatorID(operatorID);
		
		XStream xStream = new XStream();
		xStream.alias("Role", Role.class);
		xStream.toXML(roleList);
		
		
		reponseXML = xStream.toXML(roleList);
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
	}
	
	private ActionForward updateOperaotrRole(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String operatorID = request.getParameter("operatorID");
		String roleIDs = request.getParameter("roleIDs");
		
		ReturnMessage returnMessage = null;
		
		try
		{
			roleService.updateOperatorRole(operatorID,roleIDs);
			returnMessage = new ReturnMessage("1","");
		}
		catch (Exception e)
		{
			// TODO: handle exception
			returnMessage = new ReturnMessage("0",e.getMessage());
			logger.error(e);
		}
		
		String reponseXML = returnMessage.toXMLString();
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
	}
	
}